package jh.com.jhappbf.verify;

import android.content.Context;
import android.content.Intent;
import android.os.Bundle;
import android.text.TextUtils;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.BaseAdapter;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.ListView;
import android.widget.TextView;

import com.ab.activity.AbActivity;
import com.ab.fragment.AbDialogFragment;
import com.ab.model.AbMenuItem;
import com.ab.util.AbDialogUtil;
import com.ab.util.AbToastUtil;
import com.ab.view.pullview.AbPullToRefreshView;
import com.ab.view.titlebar.AbTitleBar;
import com.android.volley.Request.Priority;
import com.android.volley.Response.ErrorListener;
import com.android.volley.Response.Listener;

import org.json.JSONObject;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import androidx.core.content.ContextCompat;
import jh.com.jhappbf.R;
import jh.com.jhappbf.dispatchcar.DispatchCarQuery;
import jh.com.jhappbf.httputils.VolleyCallWebService;
import jh.com.jhappbf.httputils.VolleySingleton;
import jh.com.jhappbf.utils.JsonHelper;
import jh.com.jhappbf.view.PointDialog;

/**
 * @author Administrator
 */
public class VerifyDispatchListView extends AbActivity {

    private View mContentView;
    private View mNetErrorView;
    private Context mAppContext;
    private AbPullToRefreshView mPullToRefreshListView;
    private ListView mListView;
    private myBaseAdapter mAdapter;
    private Button mTryAgain;
    private int mCurrentPage = 1;
    private final int mPageSize = 30;
    private List<JSONObject> mData;
    private AbDialogFragment mDialogFragment;
    private AbTitleBar mAbTitleBar;
    private List<JSONObject> mTempData;
    private Map<String, String> mStateMap;
    private final int VERIFY_DISPATCH = 0x0001;
    private PointDialog pointDialog;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        mContentView = getLayoutInflater().inflate(R.layout.verify_pullrefresh_list_view, null);
        mNetErrorView = getLayoutInflater().inflate(R.layout.net_error_activity, null);
        setAbContentView(mContentView);
        mAbTitleBar = this.getTitleBar();
        mAbTitleBar.setTitleFullWidth();
        mAbTitleBar.setLogo(R.drawable.button_selector_back);
        mAbTitleBar.setTitleBarBackgroundColor(ContextCompat.getColor(this, R.color.orange));
        mAbTitleBar.setTitleTextMargin(10, 0, 10, 0);
        mAbTitleBar.setLogoLine(R.mipmap.line);
        mAppContext = getApplicationContext();
        initView();
    }

    /**
     * 初始化
     */
    private void initView() {
        mPullToRefreshListView = mContentView.findViewById(R.id.verify_pullToRefreshView);
        mListView = mContentView.findViewById(R.id.verify_query_listView);
        mData = new ArrayList<>();
        mAdapter = new myBaseAdapter();
        mListView.setAdapter(mAdapter);
        mTryAgain = mNetErrorView.findViewById(R.id.network_error_btn);
        mPullToRefreshListView.setOnHeaderRefreshListener(arg0 -> loaFirst());

        mPullToRefreshListView.setOnFooterLoadListener(arg0 -> loadMore());

        mTryAgain.setOnClickListener(v -> {
            setAbContentView(mContentView);
            refresh();
        });

        mListView.setOnItemClickListener((parent, view, position, id) -> {
            Intent intent = new Intent(VerifyDispatchListView.this, VerifyDetail.class);
            JSONObject obj = mData.get(position);
            String dispatchId = obj.optString("派车单号");
            if (dispatchId.length() == 0) {
                return;
            }
            intent.putExtra("plandId", dispatchId);
            intent.putExtra("position", position);
            intent.putExtra("operate", mAbTitleBar.getTitleTextButton().getText());
            startActivityForResult(intent, VERIFY_DISPATCH);
        });
        mListView.setOnItemLongClickListener((parent, view, position, id) -> {
            String selectOperate = mAbTitleBar.getTitleTextButton().getText().toString().trim();

            if (TextUtils.equals("未审核",selectOperate)){
                JSONObject obj = mData.get(position);
                String dispatchId = obj.optString("派车单号");
                if (dispatchId.length() == 0) {
                    return true;
                }
                pointDialog = PointDialog.show(VerifyDispatchListView.this, "请确认是否驳回该派车信息？", view1 -> {
                    deleteDispatch(dispatchId,position);
                    pointDialog.dismiss();
                });
                return true;
            }
            else {
                return false;
            }

        });

        mStateMap = new HashMap<>();
        mStateMap.put("0", "未审核");
        mStateMap.put("1", "已审核");
        mStateMap.put("2", "抽样");
        mStateMap.put("4", "化验");
        mStateMap.put("5", "一次过磅");
        mStateMap.put("6", "二次过磅");
        mStateMap.put("a", "出厂");
        setDropList();
        refresh();
    }

    /**
     * 设置标题下拉列表
     */
    private void setDropList() {
        mAbTitleBar.setTitleTextBackgroundResource(R.drawable.drop_down_selector);
        View v = getLayoutInflater().inflate(R.layout.list_pop, null);
        final ListView listView = v.findViewById(R.id.pop_list);
        final List<AbMenuItem> data = new ArrayList<>();
        data.add(new AbMenuItem("未审核"));
        data.add(new AbMenuItem("已审核"));
        ListPopAdapter mListPopAdapter = new ListPopAdapter(this, data, R.layout.item_list_pop);
        listView.setAdapter(mListPopAdapter);
        mAbTitleBar.setTitleTextDropDown(v);
        mAbTitleBar.setTitleText(data.get(0).getText());
        listView.setOnItemClickListener(new OnItemClickListener() {

            @Override
            public void onItemClick(AdapterView<?> parent, View view,
                                    int position, long id) {
                mAbTitleBar.setTitleText(data.get(position).getText());
                mAbTitleBar.hideWindow();
                refresh();
            }
        });
    }

    /**
     * 刷新和第一次加载
     */
    private void refresh() {
        mDialogFragment = AbDialogUtil.showLoadDialog(this, R.mipmap.ic_load,
                "加载中,请稍等...");
        mDialogFragment.setCancelable(false);
        mDialogFragment.setAbDialogOnLoadListener(this::loaFirst);
    }


    /**
     * 第一次加载数据
     */
    private void loaFirst() {
        mCurrentPage = 1;
        String methodName = "queryVerifyDispatch";
        ArrayList<String> params = new ArrayList<>();
        ArrayList<String> values = new ArrayList<>();
        params.add("strCurrentPage");
        params.add("strPageSize");
        params.add("flag");

        values.add(Integer.toString(mCurrentPage));
        values.add(Integer.toString(mPageSize));
        String selectOperate = mAbTitleBar.getTitleTextButton().getText().toString().trim();
        if ("已审核".equals(selectOperate)) {
            values.add("1");
        } else {
            values.add("0");
        }

        Listener<String> listener = response -> {
            AbDialogUtil.removeDialog(VerifyDispatchListView.this);
            mPullToRefreshListView.onHeaderRefreshFinish();
            mData.clear();
            List<JSONObject> newListData = JsonHelper.getJsonObjects(response);
            if (newListData.size() > 0) {
                mData.addAll(newListData);
                if (newListData.size() == mPageSize) {
                    mCurrentPage++;
                }
                mAdapter.notifyDataSetChanged();
            }
        };

        ErrorListener errorListener = error -> {
            AbDialogUtil.removeDialog(VerifyDispatchListView.this);
            mPullToRefreshListView.onHeaderRefreshFinish();
            setAbContentView(mNetErrorView);
        };

        VolleyCallWebService webService = new VolleyCallWebService(methodName,
                params, values, listener, errorListener, Priority.NORMAL);
        VolleySingleton.getVolleyInstance(mAppContext).addRequest(webService);
    }


    /**
     * 加载更多
     */
    private void loadMore() {
        String methodName = "queryVerifyDispatch";
        ArrayList<String> params = new ArrayList<>();
        ArrayList<String> values = new ArrayList<>();
        params.add("strCurrentPage");
        params.add("strPageSize");
        params.add("flag");

        values.add(Integer.toString(mCurrentPage));
        values.add(Integer.toString(mPageSize));
        String selectOperate = mAbTitleBar.getTitleTextButton().getText().toString().trim();
        if ("已审核".equals(selectOperate)) {
            values.add("1");
        } else {
            values.add("0");
        }

        Listener<String> listener = response -> {
            AbDialogUtil.removeDialog(VerifyDispatchListView.this);
            mPullToRefreshListView.onFooterLoadFinish();
            mData.clear();
            List<JSONObject> newListData = JsonHelper.getJsonObjects(response);
            if (newListData != null && newListData.size() > 0) {
                if (mTempData != null && mTempData.size() > 0) {
                    mData.clear();
                }

                mData.addAll(newListData);
                if (newListData.size() == mPageSize) {
                    mCurrentPage++;
                    mTempData = null;
                } else {
                    mTempData = newListData;
                }

                mAdapter.notifyDataSetChanged();
            }
        };

        ErrorListener errorListener = error -> {
            AbDialogUtil.removeDialog(VerifyDispatchListView.this);
            mPullToRefreshListView.onFooterLoadFinish();
            setAbContentView(mNetErrorView);
        };

        VolleyCallWebService webService = new VolleyCallWebService(methodName,
                params, values, listener, errorListener, Priority.NORMAL);
        VolleySingleton.getVolleyInstance(mAppContext).addRequest(webService);
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (data != null) {
            if (requestCode == VERIFY_DISPATCH) {
                if (resultCode == RESULT_OK) {
                    int position = data.getIntExtra("position", -1);
                    if (position > -1) {
                        mData.remove(position);
                        mAdapter.notifyDataSetChanged();
                    }
                }
            }
        }
    }

    class myBaseAdapter extends BaseAdapter {
        @Override
        public int getCount() {
            return mData.size();
        }

        @Override
        public Object getItem(int position) {
            return mData.get(position);
        }

        @Override
        public long getItemId(int position) {
            return position;
        }

        @Override
        public View getView(int position, View convertView, ViewGroup parent) {
            ViewHolder holder;
            if (convertView == null) {
                holder = new ViewHolder();
                convertView = View.inflate(mAppContext, R.layout.dispatch_car_query_list_item, null);
                holder.img = convertView.findViewById(R.id.dispatch_car_query_list_item_img);
                holder.plateNumber = convertView.findViewById(R.id.dispatch_car_query_list_item_platenum);
                holder.cargoname = convertView.findViewById(R.id.dispatch_car_query_list_item_cargoname);
                holder.states = convertView.findViewById(R.id.dispatch_car_query_list_item_state);
                holder.time = convertView.findViewById(R.id.dispatch_car_query_list_item_times);
                convertView.setTag(holder);
            } else {
                holder = (ViewHolder) convertView.getTag();
            }
            JSONObject object = mData.get(position);
            holder.id = object.optString("派车单号");
            holder.img.setBackgroundResource(R.mipmap.dispatch_car_query_item_ico);
            holder.plateNumber.setText("车号: " + object.optString("车号"));
            holder.cargoname.setText("货名: " + object.optString("货名"));
            String state = object.optString("状态");
            String overTime = object.optString("过期");
            if (mStateMap.containsKey(state)) {
                holder.states.setText("状态: " + mStateMap.get(state));
            }

            if (!TextUtils.isEmpty(overTime) && "1".equals(overTime)) {
                holder.states.setText("状态:过期");
            }

            holder.time.setText("派车时间: " + object.optString("时间"));
            return convertView;
        }
    }

    class ViewHolder {
        public String id;
        public ImageView img;
        public TextView plateNumber;
        public TextView cargoname;
        public TextView states;
        public TextView time;
    }

    /**
     * 删除
     *
     * @param id    派车单编号
     * @param index 数据的索引
     */
    private void deleteDispatch(String id, final int index) {
        mDialogFragment = AbDialogUtil.showLoadDialog(this, R.mipmap.ic_load,
                "删除中,请稍等...");
        mDialogFragment.setCancelable(false);
        String methodName = "deleteDispatch";
        ArrayList<String> param = new ArrayList<>();
        ArrayList<String> value = new ArrayList<>();
        param.add("id");
        value.add(id);
        Listener<String> listener = response -> {
            AbDialogUtil.removeDialog(VerifyDispatchListView.this);
            List<JSONObject> data = JsonHelper.getJsonObjects(response);
            if (data != null && data.size() > 0) {
                JSONObject obj = data.get(0);
                String result = obj.optString("result");
                String memo = obj.optString("memo");
                if ("true".equals(result)) {
                    mData.remove(index);
                    mAdapter.notifyDataSetChanged();
                }
                AbToastUtil.showToast(VerifyDispatchListView.this, memo);
            } else {
                AbToastUtil.showToast(VerifyDispatchListView.this, "删除失败!");
            }
        };

        ErrorListener errorListener = error -> {
            AbDialogUtil.removeDialog(VerifyDispatchListView.this);
            AbToastUtil.showToast(VerifyDispatchListView.this, "删除失败!");
        };

        VolleyCallWebService webService = new VolleyCallWebService(methodName,
                param, value, listener, errorListener, Priority.NORMAL);
        VolleySingleton.getVolleyInstance(getApplicationContext()).addRequest(
                webService);
    }
}
